package com.whh.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletResponse;

import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.springframework.web.multipart.MultipartFile;

public class FileUtils extends StrUtils {
	
	private static Logger logger = Logger.getLogger("com.harmony.utils.FileUtils");
	
	public static String getSuff(String value) {
		if(isBlank(value)) return value;
		String suffix = value.substring(value.lastIndexOf(".") + 1);
		return suffix;
	}
	public static void downloadFile(String remoteFilePath, String localFilePath){
        if(isBlank(remoteFilePath)||isBlank(localFilePath)) return ;
        if(!remoteFilePath.toLowerCase().startsWith("http:"))
        	remoteFilePath = "http:"+remoteFilePath;
		URL urlfile = null;
        HttpURLConnection httpUrl = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File f = new File(localFilePath);
        if(!f.getParentFile().exists())
			f.getParentFile().mkdir();
     
        logger.info("下载文件："+remoteFilePath+" -> "+localFilePath);
        try{
            urlfile = new URL(remoteFilePath);
            httpUrl = (HttpURLConnection)urlfile.openConnection();
            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream(f));
            int len = 2048;
            byte[] b = new byte[len];
            while ((len = bis.read(b)) != -1){
                bos.write(b, 0, len);
            }
            logger.info("下载成功");
            bos.flush();
            bis.close();
            httpUrl.disconnect();
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            try{
                bis.close();
                bos.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
	public static String readToString(String fileName) { 
		if(!isExists(fileName))
			return null;
		
        String encoding = "UTF-8";  
        File file = new File(fileName);  
        Long filelength = file.length();  
        byte[] filecontent = new byte[filelength.intValue()];  
        try {  
            FileInputStream in = new FileInputStream(file);  
            in.read(filecontent);  
            in.close();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        try {  
            return new String(filecontent, encoding);  
        } catch (UnsupportedEncodingException e) {  
        	logger.warning("系统不支撑 " + encoding);  
            e.printStackTrace();  
            return null;  
        }  
    }
	public static Boolean isExists(String fileName) {
		if(isBlank(fileName))
			return Boolean.FALSE;
		File file = new File(fileName);
		return file.exists();
	}
	public static Boolean writeToFile(String fileName,String content){
		FileOutputStream fileOutputStream = null;
	    File file = new File(fileName);
	    try {
	    	if(!file.getParentFile().exists()) {
	    		file.getParentFile().mkdirs();
	    	}
	        if(!file.exists()){
	            file.createNewFile();
	        }
            fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(content.getBytes());
            fileOutputStream.flush();
            fileOutputStream.close();
            logger.info("写入文件完成!");
            return Boolean.TRUE; 
        } catch (Exception e) {
        	e.printStackTrace();
        }
	    return Boolean.FALSE;
	}
	public static void appendToFile(String file, String conent) {
		BufferedWriter out = null;
		try {
			//out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(file),true),"UTF-8"));
			out.write(conent+"\r\n");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	public static void copyFile(String oldFile,String newFile) {
		try {
			FileInputStream input=new FileInputStream(oldFile);
	        FileOutputStream output=new FileOutputStream(newFile);
	        int in=input.read();
	        while(in!=-1){
	            output.write(in);
	            in=input.read();
	        }
	        input.close();
	        output.close();
		} catch (Exception e) {
        	e.printStackTrace();
        }
	}
	public static void backFile(String filePath,String fileName) {
		String bakName = fileName+"_"+DateUtils.getTodayCode();
		String bakFile = filePath+"/"+bakName;
		File file = new File(bakFile);
		try {
	        if(!file.exists()){
	            copyFile(filePath+"/"+fileName,bakFile);
	            logger.info("文件备份完成!");
	        }            
            
        } catch (Exception e) {
        	e.printStackTrace();
        }
	}
	public static void replaceContent(String filePath, String oldVal, String url) {
		File file = new File(filePath);
		try {
	        if(!file.exists()){
	            logger.info(filePath+"  文件不存在!");
	            return ;
	        }            
            String str = readToString(filePath);
            if(str.indexOf(oldVal)>=0) {
            	str = str.replaceAll(oldVal, url);
            	writeToFile(filePath,str);
            	logger.info("文件替换完成!");
            }
        } catch (Exception e) {
        	e.printStackTrace();
        }
	}
	
	public static void saveFile(String dest,MultipartFile file) {
		if(file.isEmpty()) return ;
		File tempFile = new File(dest);
		if(!tempFile.getParentFile().exists())
			tempFile.getParentFile().mkdirs();
		
		try {
			BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile));
			out.write(file.getBytes());
			out.flush();
			out.close();
		}catch(FileNotFoundException e) {
			e.printStackTrace();
		}catch(IOException e) {
			e.printStackTrace();
		}
	}
	public static String getSuffEx(String fileName) {
		if(isBlank(fileName)) return "";
		int idx = fileName.lastIndexOf(".");
		return fileName.substring(idx);
	}
	public static String getFileName(String fileName) {
		if(isBlank(fileName)) return "";
		int idx = fileName.lastIndexOf("/");
		return fileName.substring(idx+1);
	}
	public static Boolean download(HttpServletResponse response, String fileName) {
		if(isBlank(fileName)) 
			return Boolean.FALSE;
		
		File file = new File(fileName);
		if(!file.exists()) 
			return Boolean.FALSE;
		
		response.setContentType("application/force-download");
		response.setHeader("Content-Disposition", "attachment;fileName="+ getFileName(fileName));
		
		byte[] buffer = new byte[1024];
        FileInputStream fis = null; //文件输入流
        BufferedInputStream bis = null;
        
        OutputStream os = null; //输出流
        try {
            os = response.getOutputStream();
            fis = new FileInputStream(file); 
            bis = new BufferedInputStream(fis);
            int i = bis.read(buffer);
            while(i != -1){
                os.write(buffer);
                i = bis.read(buffer);
            }
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            bis.close();
            fis.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return Boolean.TRUE;
	}
	public static byte[] toBytes(String fileName) {
		if(isBlank(fileName))
			return null;
		File file = new File(fileName);
		if(!file.exists())
			return null;
		byte[] result = new byte[(int)file.length()];
		try {
			@SuppressWarnings("resource")
			InputStream is = new FileInputStream(file);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] bb = new byte[2048];
			int ch = is.read(bb);
			while(ch!=-1) {
				baos.write(bb,0,ch);
				ch = is.read(bb);
			}
			result = baos.toByteArray();
		}catch(Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}
	/**
     * 将svg字符串转换为png
     *
     * @param svgCode svg代码
     * @param pngFilePath 保存的路径
     * @throws TranscoderException svg代码异常
     * @throws IOException io错误
     */
    public static void convertToPng(String svgCode, String pngFilePath) throws IOException,
            TranscoderException {
 
        File file = new File(pngFilePath);
 
        FileOutputStream outputStream = null;
        try {
            file.createNewFile();
            outputStream = new FileOutputStream(file);
            convertToPng(svgCode, outputStream);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
 
    /**
     * 将svgCode转换成png文件，直接输出到流中
     *
     * @param svgCode svg代码
     * @param outputStream 输出流
     * @throws TranscoderException 异常
     * @throws IOException io异常
     */
    public static void convertToPng(String svgCode, OutputStream outputStream)
            throws TranscoderException, IOException {
        try {
            byte[] bytes = svgCode.getBytes("utf-8");
            PNGTranscoder t = new PNGTranscoder();
            TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(bytes));
            TranscoderOutput output = new TranscoderOutput(outputStream);
            t.transcode(input, output);
            outputStream.flush();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
